import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmDropdownSearch {

    text = '所有';
    checks = [];

    @bindable items;
    @bindable name;
    @bindable change;

    itemsChanged(newValue, oldValue) {
        this.checks = _.filter(this.items, 'checked');
    }

    nameChanged(newValue, oldValue) {
        this.text = `${this.name}: 所有`;
    }

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {
        $(this.ddRef).dropdown({
            action: 'nothing',
            fullTextSearch: true
        });
    }

    selectedChangedHandler() {
        this.checks = _.filter(this.items, 'checked');
        this.text = this.checks.length > 0 ? _.map(this.checks, 'name').join(', ') : `${this.name}: 所有`;
        this.change && this.change(this.checks);
    }

    initCheckboxHandler(item, chkRef) {
        _.defer(() => {
            $(chkRef).checkbox({
                onChange: () => {
                    item.checked = $(chkRef).checkbox('is checked');
                    // toastr.success('TODO...' + item.id);
                    this.selectedChangedHandler();
                }
            }).checkbox(`set ${item.checked ? 'checked' : 'unchecked'}`);
        });
    }

    clearHandler() {
        _.forEach(this.items, item => { item.checked = false; });
        this.selectedChangedHandler();
    }
}
